<?php

namespace MicroCyan\Express\Kernel;

use GuzzleHttp\Client;

class Shunfeng
{

    /**
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * 获取顺丰地址并保存数据库
     */
    public function fetchRegions(){
        //该接口用于获取顺丰最新地址版本
        $versionAPI = 'https://ucmp-static.sf-express.com/assets/config/region.json';
        $regionAPI = 'https://ucmp-static.sf-express.com/assets/data/region/region-cn-sc-${version}.json';
        try {
            $version = (new Client())->get($versionAPI)->getBody()->getContents();
            if (preg_match('/[\{\[][\s\S]*[\}\]]/',$version,$matches)){
                $version = $matches[0];
            }
            $version = json_decode($version??'{}',true)??[];
            $version = $version['check_version']??'';
        }catch (\Exception $exception){}
        $regionAPI = str_replace('${version}',$version,$regionAPI);
        try {
            $regions = (new Client())->get($regionAPI)->getBody()->getContents();
            if (preg_match('/[\{\[][\s\S]*[\}\]]/',$regions,$matches)){
                $regions = $matches[0];
            }
        }catch (\Exception $exception){}
        $regions = json_decode($regions??'{}',true)??[];
        if (!empty($regions)) {
            $this->create($regions, function ($province) {
                $this->create($province['city'] ?? [], function ($city) {
                    $this->create($city['county'] ?? [], function ($county) {

                    }, $city['areaCode'] ?? '');
                }, $province['areaCode'] ?? '');
            });
        }


    }

    private function create($regions,$fun,$parentAreaCode=''){
        foreach ($regions as $region){
            $data = array_by_field($region,'areaCode,fullName,locationCode,level');
            $data['parentAreaCode'] = is_string($parentAreaCode)?$parentAreaCode:'';
            //保存省信息
            if (empty(model('co_sf_regions')->where(array_by_field($data,'areaCode'))->value('areaCode'))){
                model('co_sf_regions')->insert($data);
            }else{
                model('co_sf_regions')->where(array_by_field($data,'areaCode'))->save($data);
            }
            $fun($region);
        }
    }

}